<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-form-item label="模块名" prop="name">
        <el-input v-model="formData.name" placeholder="请输入模块名" />
      </el-form-item>
      <el-form-item label="模块编码" prop="code">
        <el-input v-model="formData.code" placeholder="请输入模块编码" />
      </el-form-item>
      <el-form-item label="web地址" prop="webBaseUrl">
        <el-input v-model="formData.webBaseUrl" placeholder="请输入模块web地址" />
      </el-form-item>
      <el-form-item label="api地址" prop="apiBaseUrl">
        <el-input v-model="formData.apiBaseUrl" placeholder="请输入模块api地址" />
      </el-form-item>
      <el-form-item label="h5地址" prop="h5BaseUrl">
        <el-input v-model="formData.h5BaseUrl" placeholder="请输入h5地址" />
      </el-form-item>
      <el-form-item label="app h5地址" prop="appH5BaseUrl">
        <el-input v-model="formData.appH5BaseUrl" placeholder="请输入app h5地址地址" />
      </el-form-item>
      <!-- appH5BaseUrl -->
      <el-form-item label="webhook" prop="webhookPath">
        <el-input v-model="formData.webhookPath" placeholder="请输入模块webhook路径" />
      </el-form-item>
      <el-form-item label="登录地址" prop="loginUrl">
        <el-input v-model.trim="formData.loginUrl" placeholder="请输入模块登录地址" />
      </el-form-item>
      <el-form-item label="图片地址" prop="imgUrl">
        <el-input v-model.trim="formData.imgUrl" placeholder="请输入模块图片地址" />
      </el-form-item>
      <el-form-item label="显示顺序" prop="sort">
        <el-input-number v-model="formData.sort" :min="0" clearable controls-position="right" />
      </el-form-item>
      <el-form-item label="是否同步数据" prop="sync">
        <el-switch v-model="formData.sync" :active-value="true" :inactive-value="false" />
      </el-form-item>
      <el-form-item label="登陆配置">
        <el-card class="box-card" style="width: 100%">
          <el-row>
            <el-col :span="4">webLoginUrl</el-col>
            <el-col :span="20">
              <el-input v-model="formData.loginConfig.webLoginUrl" />
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="4">appLoginUrl</el-col>
            <el-col :span="20">
              <el-input v-model="formData.loginConfig.appLoginUrl" />
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="4">header</el-col>
            <el-col :span="20">
              <el-input v-model="formData.loginConfig.header" type="textarea" />
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="4">body</el-col>
            <el-col :span="20">
              <el-input v-model="formData.loginConfig.body" type="textarea" />
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="4">successKey</el-col>
            <el-col :span="20">
              <el-input v-model="formData.loginConfig.successKey" />
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="4">successCode</el-col>
            <el-col :span="20">
              <el-input v-model="formData.loginConfig.successCode" />
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="4">userId</el-col>
            <el-col :span="20">
              <el-input v-model="formData.loginConfig.userId" />
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="4">accessToken</el-col>
            <el-col :span="20">
              <el-input v-model="formData.loginConfig.accessToken" />
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="4">refreshToken</el-col>
            <el-col :span="20">
              <el-input v-model="formData.loginConfig.refreshToken" />
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="4">expiresTime</el-col>
            <el-col :span="20">
              <el-input v-model="formData.loginConfig.expiresTime" />
            </el-col>
          </el-row>
        </el-card>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import * as ModuleApi from '@/api/system/module'

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  name: undefined,
  code: undefined,
  webBaseUrl: undefined,
  apiBaseUrl: undefined,
  h5BaseUrl: undefined,
  appH5BaseUrl: undefined,
  webhookPath: undefined,
  loginUrl: undefined,
  imgUrl: undefined,
  sort: Number(undefined),
  sync: false,
  loginConfig: {
    webLoginUrl: undefined,
    appLoginUrl: undefined,
    header: undefined,
    body: undefined,
    successKey: undefined,
    successCode: undefined,
    userId: undefined,
    accessToken: undefined,
    refreshToken: undefined,
    expiresTime: undefined
  }
})
const formRules = reactive({
  name: [{ required: true, message: '模块名不能为空', trigger: 'blur' }],
  code: [{ required: true, message: '模块编码不能为空', trigger: 'blur' }],
  webBaseUrl: [{ required: true, message: '模块web地址不能为空', trigger: 'blur' }],
  apiBaseUrl: [{ required: true, message: '模块api地址不能为空', trigger: 'blur' }],
  webhookPath: [{ required: true, message: '模块webhook路径不能为空', trigger: 'blur' }],
  loginUrl: [{ required: true, message: '模块登录地址不能为空', trigger: 'blur' }],
  imgUrl: [{ required: true, message: '模块图片地址不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await ModuleApi.getModule(id)
      if (!formData.value.loginConfig) {
        formData.value.loginConfig = {
          webLoginUrl: undefined,
          appLoginUrl: undefined,
          header: undefined,
          body: undefined,
          successKey: undefined,
          successCode: undefined,
          userId: undefined,
          accessToken: undefined,
          refreshToken: undefined,
          expiresTime: undefined
        }
      }
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  if (!formRef.value) return
  const valid = await formRef.value.validate()
  if (!valid) return
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as ModuleApi.ModuleVO
    if (formType.value === 'create') {
      await ModuleApi.createModule(data)
      message.success(t('common.createSuccess'))
    } else {
      await ModuleApi.updateModule(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    name: undefined,
    code: undefined,
    webBaseUrl: undefined,
    apiBaseUrl: undefined,
    h5BaseUrl: undefined,
    webhookPath: undefined,
    loginUrl: undefined,
    imgUrl: undefined,
    sync: false,
    loginConfig: {
      webLoginUrl: undefined,
      appLoginUrl: undefined,
      header: undefined,
      body: undefined,
      successKey: undefined,
      successCode: undefined,
      userId: undefined,
      accessToken: undefined,
      refreshToken: undefined,
      expiresTime: undefined,
      sort: Number(undefined)
    }
  }
  formRef.value?.resetFields()
}
</script>
